package com.baizhi.service.impl;

import com.baizhi.dao.OrderDao;
import com.baizhi.entity.Order;
import com.baizhi.service.OrderService;
import com.baizhi.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.List;

public class OrderServiceImpl implements OrderService {
    @Override
    public List<Order> selectAllOrder() {
        List<Order> orders=new ArrayList<>();
        SqlSession sqlSession= MyBatisUtils.openSession();
        try {
            OrderDao orderDao = sqlSession.getMapper(OrderDao.class);
            orders=orderDao.selectAllOrder();
            sqlSession.commit();
        }catch (Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw new RuntimeException(e);
        }
        finally {
            MyBatisUtils.close(sqlSession);
        }
        return orders;
    }

    @Override
    public Order selectOrderById(String orderId) {
        Order order=null;
        SqlSession sqlSession= MyBatisUtils.openSession();
        try {
            OrderDao orderDao = sqlSession.getMapper(OrderDao.class);
            order = orderDao.selectOrderById(orderId);
            sqlSession.commit();
        }catch (Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw new RuntimeException(e);
        }
        finally {
            MyBatisUtils.close(sqlSession);
        }
        return order;
    }

    @Override
    public void addOrder(Order order) {
        SqlSession sqlSession= MyBatisUtils.openSession();
        try {
            OrderDao orderDao = sqlSession.getMapper(OrderDao.class);
            orderDao.addOrder(order);
            sqlSession.commit();
        }catch (Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw new RuntimeException(e);
        }
        finally {
            MyBatisUtils.close(sqlSession);
        }
    }

    @Override
    public void updateOrderPayStatus(Order order) {
        SqlSession sqlSession= MyBatisUtils.openSession();
        try {
            OrderDao orderDao = sqlSession.getMapper(OrderDao.class);
            orderDao.updateOrderPayStatus(order);
            sqlSession.commit();
        }catch (Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw new RuntimeException(e);
        }
        finally {
            MyBatisUtils.close(sqlSession);
        }
    }
}
